using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace CodePlex.Resourceful
{
    public class MonitoredStream : DecoratedStream
    {
        private Encoding _encoding = Encoding.Default;
        private readonly Action<string> _write;

        public MonitoredStream(Stream stream, Action<string> write)
            : base(stream)
        {
            _write = write;
        }


     

        override public int Read(byte[] buffer, int offset, int count)
        {

           
            int read = base.Read(buffer, offset, count);
          
            if (read == 0)
            {
                return read;
            }



            int skip = 0;

            byte[] utf8bom = new byte[] { 0xef, 0xbb, 0xbf };

            if (offset == 0 && buffer.Length >= 3
                && buffer[0] == utf8bom[0]
                && buffer[1] == utf8bom[1]
                && buffer[2] == utf8bom[2])
            {
                
                skip = 3;
                _encoding = Encoding.UTF8;
            }

           
            string s = _encoding.GetString(buffer, offset + skip, read - skip);

            _write(s);
           
            return read;

        }



        public override void Write(byte[] buffer, int offset, int count)
        {

            string s = _encoding.GetString(buffer, offset, count);
            _write(s);


           
            base.Write(buffer, offset, count);
        }


     
    }

}
